package com.etrans.web.gps.business.report.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.etrans.web.gps.base.service.BaseService;
import com.etrans.web.gps.business.report.domain.HistoryImgVO;
import com.etrans.web.gps.business.report.domain.HistoryPicChart;
import com.etrans.web.gps.business.report.domain.HistoryPicVO;
import com.etrans.web.gps.common.Constant;
import com.etrans.web.gps.common.MGTemplete;
import com.etrans.web.gps.util.Config;
import com.etrans.web.gps.util.DateUtil;
import com.etrans.web.gps.util.EgovUtil;
import com.etrans.web.gps.util.map.GpsToGaoDe;
import com.mongodb.QueryOperators;

/**
 * 历史图片
 * @author yin
 * 2017/06/28
 */
@Service
public class HisPicService extends BaseService{
	@Autowired
	private Config config; //引用统一的参数配置类 
//	@Autowired
//	private EcpmUtil ecpmUtil;
    @Autowired
    private EgovUtil egovUtil;
    

	/**
	 * 车辆图片统计
	 * @param vehicleId
	 * @param startTime
	 * @param endTime
	 * @param enterprisseId
	 * @return
	 */
	public HistoryPicChart queryChartData(String vehicleNo, String startTime, String endTime, String enterprisseId) {
		//处理查询条件
		HashMap<String,Object> whereMap = new HashMap<String, Object>();
		HashMap<String,Object> whereMap_Time = new HashMap<String, Object>();
		HashMap<String,Object> whereMap_vehicleList = new HashMap<String, Object>();
		Map<String,Object> param = new HashMap<String,Object>();
		List<String> dateList = DateUtil.getDates(startTime,endTime);
		try {
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date start_Time = format.parse(startTime + " 00:00:00");
			Date end_Time = format.parse(endTime + " 23:59:59");
			if ( null != vehicleNo && !"".equals(vehicleNo)) {
				whereMap.put("vehicle_no", vehicleNo);
			}
			//业户待定
			if ( null != enterprisseId && !"".equals(enterprisseId)) {
				param.put("enterprisseId", enterprisseId);
				List<String> vehicleList = this.selectList("historyPicQuery.queryVehicleNoList", param);
				whereMap_vehicleList.put(QueryOperators.IN,vehicleList);
				whereMap.put("vehicle_no", whereMap_vehicleList);
			}
			if (null != startTime && !"".equals(startTime)) {
				whereMap_Time.put("$gte", start_Time);	//大于
			}
			if (null != endTime && !"".equals(endTime)) {
				whereMap_Time.put("$lte", end_Time);		//小于
			}
			whereMap.put("gps_time", whereMap_Time);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		List<Object> historyImgList = new ArrayList<>();
		for(int i=0;i<dateList.size();i++){
			String tableName = "img_info_"+DateUtil.getDateTimeString(DateUtil.getDate(dateList.get(i)), "yyMMdd");
			List<Object> historyImgtemp=MGTemplete.groupBy("egov", tableName, whereMap, "vehicle_no", null, 0);
			historyImgList.addAll(historyImgtemp);
		}
		List<String> barXAxisData = new ArrayList<String>();
		List<Integer> barSeriesData = new ArrayList<Integer>();
		if (historyImgList.size()>0) {
			for (Object obj : historyImgList) {
				String jsonStr = JSONObject.toJSONString(obj);
				JSONObject json = JSON.parseObject(jsonStr);
				String vehicle_no = String.valueOf(json.get("_id")).split(":")[0];
				if(barXAxisData.contains(vehicle_no)){
					int index = barXAxisData.indexOf(vehicle_no);
					int count = barSeriesData.get(index);
					count += Integer.parseInt(String.valueOf(json.get("count")));
					barSeriesData.set(index, count);
				}else{
					barXAxisData.add(vehicle_no);
					barSeriesData.add(Integer.parseInt(String.valueOf(json.get("count"))));
				}
			}
		}
		HistoryPicChart chart = new HistoryPicChart();
		chart.setxAxisData(barXAxisData);
		chart.setSeries(barSeriesData);
		return chart;
	}
	
	/**
	 * 查询车辆的历史图片
	 * @param vehicleId
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	public List<HistoryImgVO> queryPicListByVehicleNo(String vehicleNo, String startTime, String endTime) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//处理查询条件
		HashMap<String,Object> whereMap = new HashMap<String, Object>();
		HashMap<String,Object> whereMap_Time = new HashMap<String, Object>();
		List<HistoryImgVO> historyImgList=new ArrayList<HistoryImgVO>();
		List<String> dateList = DateUtil.getDates(startTime,endTime);
		if ( null != vehicleNo && !"".equals(vehicleNo)) {
			whereMap.put("vehicle_no", vehicleNo);
			
			try {
				if (null != startTime && !"".equals(startTime)) {
					whereMap_Time.put("$gte", format.parse(startTime));	//大于
				}
				if (null != endTime && !"".equals(endTime)) {
					whereMap_Time.put("$lte", format.parse(endTime));		//小于
				}
				whereMap.put("gps_time", whereMap_Time);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			for(int i=0;i<dateList.size();i++){
				String tableName = "img_info_"+DateUtil.getDateTimeString(DateUtil.getDate(dateList.get(i)), "yyMMdd");
				List<HistoryImgVO> historyImgtemp=MGTemplete.find("egov", tableName, whereMap, HistoryImgVO.class,true);
				historyImgList.addAll(historyImgtemp);
			}
		}
		
		HashMap<String,String> vehicleMap = new HashMap<String, String>();
		List<HashMap<String, Object>> vehicleList = this.selectList("historyPicQuery.queryVehicleColor", null);
		for (HashMap<String, Object> hashMap : vehicleList) {
			vehicleMap.put((String) hashMap.get("code"), (String) hashMap.get("name"));
		}
		
		List<HistoryImgVO> historyList=new ArrayList<HistoryImgVO>();
		for (HistoryImgVO vo : historyImgList) {
			double longitude = vo.getCoordinates().getCoordinates()[0];
			double latitude = vo.getCoordinates().getCoordinates()[1];
			if(longitude>0 && latitude>0){
				long gpsTime=vo.getGps_time().getTime();
				String imageFileName = egovUtil.getImageFileName(vo.getVehicle_id(), vo.getLens_id(), gpsTime);
				vo.setImgUrl(config.imagePath+imageFileName);
				for(Entry<String, String> map : vehicleMap.entrySet()){
					String str=vo.getVehicle_color()+"";
					if(str.equals(map.getKey())){
						vo.setVehicle_no(vo.getVehicle_no()+" ("+map.getValue()+")");
						break;
					}
				}
				//状态解析
				
				int state = vo.getState();
				vo.setStatus(Constant.C_GPS_FlAG_VALID == (Constant.C_GPS_FlAG_VALID & (byte)state));			
				
				double[] gdLatlon=GpsToGaoDe.transform(latitude, longitude);			
				vo.setGdLat(gdLatlon[0]);
				vo.setGdLng(gdLatlon[1]);			
				vo.setGpsTimeStr(format.format(vo.getGps_time()));
				historyList.add(vo);
			}
		}
		
		return historyList;
	}
	
	
	/**
	 * 查询车辆的历史图片
	 * @param vehicleId
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	public List<HistoryPicVO> queryPicListByVehicleId(String vehicleId, String startTime, String endTime) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String monthStr = startTime.substring(0, 7);
		monthStr = monthStr.replace("-", "_");
		
		String emonthStr = endTime.substring(0, 7);
		emonthStr = emonthStr.replace("-", "_");
		
		List<HistoryPicVO> list= new ArrayList<HistoryPicVO>();
		List<HistoryPicVO> slist= new ArrayList<HistoryPicVO>();
		List<HistoryPicVO> elist= new ArrayList<HistoryPicVO>();
		
		paramMap.put("vehicleId", vehicleId);
		paramMap.put("startTime", startTime);
		paramMap.put("endTime", endTime);
		paramMap.put("tableName", "sys_image_" + monthStr);
		slist = selectList("historyPicQuery.queryPicListByVehicleId", paramMap);
		list.addAll(slist);
		
		
		if(emonthStr.equals(monthStr)){
			
		}else{
			paramMap.put("vehicleId", vehicleId);
			paramMap.put("startTime", startTime);
			paramMap.put("endTime", endTime);
			paramMap.put("tableName", "sys_image_" + emonthStr);
			elist = selectList("historyPicQuery.queryPicListByVehicleId", paramMap);
			list.addAll(elist);
			
		}
		for(HistoryPicVO vo : list){
			if(vo.getLongitude()<100){//经纬度为空，则去轨迹表去数据
				Map trackParamMap = new HashMap();
				Date gpsTime = vo.getGpsTime();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String dateStr = sdf.format(gpsTime);
				
				Map trackMap = (Map)this.selectOne("historyPicQuery.queryLatestTrack", trackParamMap);
				if(trackMap!=null){
					vo.setLongitude(Long.parseLong(trackMap.get("longitude").toString()));
					vo.setLatitude(Long.parseLong(trackMap.get("latitude").toString()));
					vo.setGpsSpeed(Float.parseFloat(trackMap.get("gps_speed").toString()));
					vo.setStatus(trackMap.get("status").toString());
				}
			}
			
			double latitude = (double)vo.getLatitude()/(double)1000000;
			double longitude = (double)vo.getLongitude()/(double)1000000;
			double[] gdLatlon=GpsToGaoDe.transform(latitude, longitude);			
			double gdLat = (int)(gdLatlon[0]*1000000)/(double)1000000;
			double gdlng = (int)(gdLatlon[1]*1000000)/(double)1000000;
			vo.setGdLat(gdLat);
			vo.setGdLng(gdlng);			
			vo.setGpsTimeStr(dateFormat.format(vo.getGpsTime()));
		}
		
		return list;
	}
	
	/**
	 * 查询车牌
	 * @param areaId
	 * @return
	 */
	public List<HashMap<String, Object>> queryVeList(Integer areaId) {
		Map<String,Object> param = new HashMap<>();
		param.put("FullID",String.format("%08d", areaId));
		return this.selectList("historyPicQuery.queryVeList", param);
	}
}
